import { Injectable, Directive } from '@angular/core'
import { Http, Jsonp } from '@angular/http';

import { File } from './../models/file'

import 'rxjs/add/operator/toPromise';

// const fileMockUrl = 'http://localhost:3000/user/getFiles';

const files: File[] = [
  {
    id: 1,
    name: '双均线策略',
    content: 'ma30 和 ma60 金叉买入 死叉卖出'
  },

  {
    id: 2,
    name: '招行伊利轮动策略',
    content: '招商银行和伊利股份轮动操作'
  },

  {
    id: 3,
    name: '这是一个简单的策略-1',
    content: '默认新建策略'
  },

  {
    id: 4,
    name: '这是一个简单的策略-2',
    content: '默认新建策略'
  },

  {
    id: 5,
    name: '这是一个简单的策略-3',
    content: '默认新建策略'
  },

  {
    id: 6,
    name: '这是一个简单的策略-4',
    content: '默认新建策略'
  },

  {
    id: 7,
    name: '这是一个简单的策略-5',
    content: '默认新建策略'
  },

  {
    id: 8,
    name: '这是一个简单的策略-6',
    content: '默认新建策略'
  }
]

@Injectable()
export class FileService {
  private data: any = {};

  public save(key: any, data: any) {
    this.data[key] = data;
  }

  public get(key: any) {

    if(this.data.hasOwnProperty(key)) {
      return this.data[key];
    } else {
      return false;
    }
  }

  constructor(
    private http: Http,
    private jsonp: Jsonp
  ) {}

  getFiles(): Promise<File[]> {
    // return this.jsonp.get(fileMockUrl)
    //   .toPromise()
    //   .then(result => result.json().result as File[])
    return Promise.resolve(files)
  }

  getFile(id: number): Promise<File> {
    return this.getFiles()
      .then(files => files.find(file => file.id === id))
  }

  getFilesSlowly(): Promise<File[]> {
    console.log(this.get('files'));

    if (this.get('files')) {
      return Promise.resolve(this.get('files')) ;
    }
    else {
      return new Promise(resolve => {
        setTimeout(() => {
          this.save('files', this.getFiles())
          console.log(this.get('files'));
          resolve(this.getFiles())
        }, 5000);
      });
    };
  }

  getFileSlowly(id: number): Promise<File> {

    if (this.get('file_' + id)) {
      return Promise.resolve(this.get('file_' + id)) ;
    }
    else {
      return new Promise(resolve => {
        setTimeout(() => {
          this.save('file_' + id, this.getFile(id))
          console.log(this.get('file_' + id));
          resolve(this.getFile(id))
        }, 5000);
      });
    };
  }
}
